package cn.study.luckyinfrastructure.gateway.iml;

import cm.study.config.enums.LdExeceptionEnum;
import cm.study.config.util.AssertUtil;
import cn.study.luckydomain.User.UserEntity;
import cn.study.luckydomain.gateway.UserGateway;
import cn.study.luckyinfrastructure.convertor.UserConvertor;
import cn.study.luckyinfrastructure.gateway.iml.dataObject.UserDB;
import cn.study.luckyinfrastructure.gateway.iml.mapper.UserMapper;
import com.alibaba.cola.exception.SysException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.mapstruct.control.MappingControl;
import org.springframework.stereotype.Component;

import java.util.Objects;

@Slf4j
@Component
@AllArgsConstructor
public class UserGatewayImpl implements UserGateway {
    private UserMapper userMapper;
    @Override
    public UserEntity save(UserEntity userEntity) {
        UserDB userDB = UserConvertor.toUserDB(userEntity);
        int insert = userMapper.insert(userDB);
        AssertUtil.isTrue(insert<1, LdExeceptionEnum.ADD_ERROR.getDescription());
        return UserConvertor.toEntity(userDB);
    }

    @Override
    public UserEntity findByUserName(Long id, String username) {
        UserDB userDB = userMapper.findByUserName(id, username);
        if (Objects.isNull(userDB)) {
            return null;
        }
        return UserConvertor.toEntity(userDB);
    }

    @Override
    public UserEntity updateByUserName(UserEntity userEntity) {
        UserDB userDB = UserConvertor.toUserDB(userEntity);
        QueryWrapper<UserDB> objectQueryWrapper = new QueryWrapper<>();
        objectQueryWrapper.eq("id",userDB.getId());
        userMapper.update(userDB,objectQueryWrapper);
        UserEntity userEntity1 = UserConvertor.toEntity(userDB);
        return userEntity1;
    }

    @Override
    public UserEntity one(Long id) {
        QueryWrapper<UserDB> objectQueryWrapper = new QueryWrapper<>();
        objectQueryWrapper.eq("id",id);
        UserDB userDB = userMapper.selectOne(objectQueryWrapper);
        UserEntity userEntity = UserConvertor.toEntity(userDB);
        return userEntity;
    }
}
